package org.s45.erp.auth;

import com.ttxs.common.core.vo.LoginUser;
import com.ttxs.common.core.vo.R;
import com.ttxs.common.security.util.AuthUtils;
import lombok.extern.slf4j.Slf4j;
import org.s45.erp.api.RemoteAuthService;
import org.s45.erp.api.params.LoginResult;
import org.s45.erp.api.params.UserParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@Slf4j
public class AuthController {
    @Resource
    private RemoteAuthService remoteAuthService;

    @PostMapping("/login")
    public R<LoginResult> login(@RequestBody UserParam userParam) {
        log.info("认证中心login:{}", userParam);
        R<LoginResult> result = remoteAuthService.login(userParam);
        // 缓存登录信息，方便网关鉴权
        cacheLogin(result.getData(), result.getData().getToken());
        return result;
    }

    @GetMapping("/logout")
    public R logout(@RequestHeader(name = "X-Access-Token") String token) {
        log.info("认证中心logout");
        removeCache(token);
        return remoteAuthService.logout();
    }


    @PostMapping(value = "/registerUser")
    public R registerUser(@RequestBody UserParam userParam) {
        log.info("认证中心registerUser:{}", userParam);
        return remoteAuthService.registerUser(userParam);
    }

    private void cacheLogin(LoginResult loginResult, String token) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(loginResult.getUser().getId());
        loginUser.setUsername(loginResult.getUser().getLoginName());
        loginUser.setNickName(loginResult.getUser().getUsername());
        // 本系统不是标准的rbac，所以urlPatterns为空
        loginUser.setUrlPatterns(null);
        // 本系统不是标准的rbac，通过extra存储了权限名字
        loginUser.setExtra(loginResult.getFuncList());
        AuthUtils.createToken(loginUser, token);
    }

    private void removeCache(String token) {
        AuthUtils.removeToken(token);
    }

}
